package com.example.mp.modular.system.controller;

import com.example.mp.config.web.WxMpConfiguration;
import com.example.mp.core.common.JsonUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/wx/redirect/{appid}")
public class WxRedirectController {
    @Value("${spring.application.name}")
    private String applicationName;

    @RequestMapping("/currentUser")
    public String user(@PathVariable String appid, @RequestParam String code, ModelMap map) {
        System.out.println("code：" + code);
        WxMpService mpService = WxMpConfiguration.getMpServices().get(appid);
        map.put("applicationName", applicationName);
        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
            map.put("user", user);
            map.put("userJson", JsonUtil.toJson(user));
            System.out.println(map.get("userJson").toString());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "redirect/user";
    }
}
